<template>
    <div class="role-box">
        <div class="p-menu flex">
            <div class="p-menu-left flex flex-left">
                <el-input v-model="queryParams.keywords" class="p-i1" placeholder="角色名称" />

                <el-select v-model="queryParams.platformId" placeholder="平台" class="p-i3" style="height: 38px;"
                    v-show="userData.username == 'root'">
                    <el-option v-for="item in platformList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>

                <el-button color="#FABD68" class="p-button" @click="query()">查询</el-button>
            </div>

            <div class="p-menu-right flex flex-right">
                <el-button color="#2CA6E0" class="p-button" @click="setDialogVisible(null)">新建角色</el-button>
            </div>
        </div>
        <div class="p-ul-box">
            <el-table :data="submitList" style="width: 100%" class="p-ul" v-loading="loading">
                <el-table-column prop="id" label="序号" align="center" />
                <el-table-column prop="name" label="名称" align="center " />
                <el-table-column prop="platformId" label="平台" align="center ">
                    <template #default="scope">
                        <text>{{ getPlatformName(scope.row.platformId) }}</text>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center ">
                    <template #default="scope">
                        <el-button link type="info" size="small" style="color:black;"
                            @click="setDialogVisible(scope.row)">编辑</el-button>
                        <el-button link type="danger" size="small" @click="deleteRole(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="p-end flex">
            <div class="flex-left">共有{{ total }}项数据</div>
            <el-pagination class="flex-right" style="margin-right:50px;" v-model:current-page="queryParams.page"
                @current-change="currentChange" v-model:page-size="queryParams.size" layout="prev, pager, next, jumper"
                :total="total" />
        </div>

        <!-- 新增or编辑 -->
        <el-dialog v-model="dialogVisible" :title="visibleTitle" width="746" class="role-add">
            <el-form :model="form" label-width="120px">
                <el-form-item label="名称">
                    <el-input v-model="form.name" style="width:240px;" placeholder="名称" />
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" style="width:240px;" placeholder="备注" />
                </el-form-item>
                <el-form-item label="基础权限">
                    <el-scrollbar style="height: 100px; width: 500px;">
                        <el-checkbox-group v-model="roleBasicsArrayCheck" @change="roleBasicsArrayCheckChange"
                            style="display: flex;flex-wrap: wrap;">
                            <el-checkbox v-for="city in roleBasicsArr" :label="city" :key="city.id"
                                style="width: 100px;white-space: nowrap; text-overflow: ellipsis;"
                                :checked="isBasicRoleSelected(city)">{{ city.name }}</el-checkbox>
                        </el-checkbox-group>


                    </el-scrollbar>

                </el-form-item>
                <el-form-item label="权限设置">
                    <div>
                        <div class="flex role-tree-box">
                            <div> <el-scrollbar class="role-tree">
                                    <el-tree class="tree-border" :data="dataArray" node-key="id" @check-change="checkChange"
                                        :props="defaultProps" ref="myTree" @node-click="handleNodeClick"
                                        empty-text="加载中，请稍候"></el-tree>

                                </el-scrollbar></div>
                            <div class="flex-right role-right" v-show="roleArray.length != 0">
                                <el-scrollbar>
                                    <div style="margin: 15px 0;"></div>
                                    <el-checkbox-group v-model="roleArrayCheck" @change="handleCheckedCitiesChange">
                                        <el-checkbox v-for="city in roleArray" :label="city" :key="city.id"
                                            :checked="isRoleSelected(city)">{{ city.name }}</el-checkbox>
                                    </el-checkbox-group>
                                </el-scrollbar>
                            </div>
                        </div>
                    </div>
                </el-form-item>


            </el-form>
            <template #footer>

                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="postSubmit"> 确定 </el-button>
                </span>
            </template>
        </el-dialog>





    </div>
</template>
  
<script setup>

import {
    ref,
    getCurrentInstance,
    onMounted,
} from "vue";
import { ElMessage } from 'element-plus'
// import RoleMenu from "@/components/RoleMenu/index.vue";

const {
    proxy
} = getCurrentInstance();

const loading = ref(false);


//查询条件
const queryParams = ref({
    keywords: null,
    platformId: null,
    size: 30,
    page: 1,
})

const userData = ref({})
const platformName = ref('');
const platformId = ref();

const submitList = ref([]);//集合数据
const total = ref(0);
const roleArray = ref([]);//查询出来的权限数据
const roleArrayCheck = ref([]);//查询出来并且选中的数组
const roleList = ref([]);//用户拥有的权限列表
const roleBasicsArr = ref([]);//基础权限
const roleBasicsArrayCheck = ref([]);//查出来并且选中的

const dataArray = ref([])
const defaultProps = {
    children: 'children',
    label: 'label',
};
const form = ref({
    id: null,
    name: null,
    platformId: null,
    remark: null,
    authIds: null,
})




onMounted(() => {
    getPlatformList();//获取平台
    //实际数据方法
    getSubmitList();
    getUser();
});

function getUser() {
    const savedData = localStorage.getItem('USERINFO');
    const obj = JSON.parse(savedData);
    userData.value = obj;
    //console.log(userData.value.username)
    if (userData.value.platform != null) {
        platformName.value = userData.value.platform.name;
        platformId.value = userData.value.platform.id;
        queryParams.value.platformId = userData.value.platform.id;
    }
    getMenuListTree();
}

function postSubmit() {//修改角色权限

    //1.将已查询出展示的列表删除 然后将已经选好的权限加入post数组
    let query = [];
    query = query.concat(roleBasicsArr.value);
    query = query.concat(roleArray.value);
    const filteredList = roleList.value.filter(role => !query.some(item => item.id === role.id));//菜单权限
    roleList.value = filteredList;
    //2.然后将已经选好的权限加入到用户拥有权限roleList+roleArrayCheck
    roleList.value = roleList.value.concat(roleArrayCheck.value);
    roleList.value = roleList.value.concat(roleBasicsArrayCheck.value);
    //3.使用 map 方法提取每个对象的 id 属性
    const idArray = roleList.value.map(item => item.id);
    const ids = idArray.join(',');
    //console.log(ids);
    const data = {
        id: form.value.id,
        name: form.value.name,
        platformId: platformId.value,
        remark: form.value.remark,
        authIds: ids
    }
    proxy.$Request.post(proxy.$urlApi.role.submit, data)
        .then((res) => {
            if (res.data.code == 200) {
                dialogVisible.value = false;
                ElMessage({
                    message: '新增成功',
                    type: 'success',
                })
                getSubmitList();
            } else {
                ElMessage({
                    message: res.data.msg,
                    type: 'error',
                })
            }
        }).catch(error => {
            ElMessage({
                message: "提交失败",
                type: 'error',
            })
        });
}


function getSubmitList() {//获取列表数据
    const data = queryParams.value;
    loading.value = true;
    proxy.$Request.get(proxy.$urlApi.role.list, data)
        .then((res) => {
            submitList.value = res.data.data;
            total.value = submitList.value.length
            loading.value = false;
        }).catch(error => {
            // 处理 Promise 拒绝的情况
            // console.error(error); // 输出错误信息
            loading.value = false;
        });
}

function query() {
    queryParams.value.page = 1;
    getSubmitList();
}


//权限树形点击事件
function handleNodeClick(node, check) {
    getMenuAuth(node.id);
}


function getRoleByMenu(id) {//根据目录id查询权限
    const data = {
        roleId: id,
    }
    proxy.$Request.get(proxy.$urlApi.roleAuth.getIds, data)
        .then((res) => {
            if (res.data.code != 200) {
                ElMessage({
                    message: '123',
                    type: 'error',
                })
            } else {
                const arrObject = res.data.data.split(',');//分为数组
                roleList.value = arrObject.map((str) => {
                    return { id: (str * 1), name: "" };
                });
            }
        }).catch(error => {
            ElMessage({
                message: row.id + '获取失败',
                type: 'error',
            })
        });
}


//获取平台基础权限
function getBasicsList() {
    const data = {
        platformId: platformId.value
    }
    proxy.$Request.get(proxy.$urlApi.auth.list, data)
        .then((res) => {
            if (res.data.code == 200) {
                //1.基础菜单的全部数据
                roleBasicsArr.value = res.data.data;

                if (form.authIds != null) {
                    roleList
                }
                for (const roleListItem of roleBasicsArr.value) {
                    // 检查是否在 roleArray 中存在相同的 id
                    const found = roleArray.value.find((roleArrayItem) => roleArrayItem.id === roleListItem.id);
                    if (found) {
                        roleBasicsArrayCheck.value.push(found);
                    }
                }

            }
        }).catch(error => {
        });
}




async function getMenuAuth(id) {//查询菜单权限
    const data = {
        menuId: id,
        platformId: platformId.value,
    }
    proxy.$Request.get(proxy.$urlApi.auth.list, data)
        .then((res) => {
            // form.value = res.data.data;
            if (res.data.code != 200) {
                ElMessage({
                    message: res.data.msg,
                    type: 'error',
                })
            } else {
                //1.删除上一个菜单拥有的全部权限roleList-roleArray
                const filteredList = roleList.value.filter(role => !roleArray.value.some(item => item.id === role.id));
                // console.log("上一个菜单的权限");
                // console.log(roleArray.value);
                roleList.value = filteredList;
                //2.然后将已经选好的权限加入到用户拥有权限roleList+roleArrayCheck
                roleList.value = roleList.value.concat(roleArrayCheck.value);
                //3.根据自己拥有的权限，去查找这里面是否有自己的权限，如果有就将值加到roleList对比roleArray = roleArrayCheck
                roleArray.value = res.data.data; //这个新菜单全部的权限
                roleArrayCheck.value = [];
                // 遍历 roleList  
                for (const roleListItem of roleList.value) {
                    // 检查是否在 roleArray 中存在相同的 id
                    const found = roleArray.value.find((roleArrayItem) => roleArrayItem.id === roleListItem.id);
                    if (found) {
                        roleArrayCheck.value.push(found);
                    }
                }
            }


        }).catch(error => {
            ElMessage({
                message: '提交失败',
                type: 'error',
            })
        });
}


function isRoleSelected(city) {
    // 使用 some 方法检查 roleList 是否包含 city
    return roleList.value.some(role => role.id === city.id);
}
function handleCheckedCitiesChange(checkedRoles) {
    // 处理选中状态改变时的逻辑
    roleArrayCheck.value = checkedRoles;
    //console.log(roleArrayCheck.value);
}
function isBasicRoleSelected(city) {
    // 使用 some 方法检查 roleList 是否包含 city
    return roleList.value.some(role => role.id === city.id);
}

function roleBasicsArrayCheckChange(checkedRoles) {
    // 处理选中状态改变时的逻辑
    roleBasicsArrayCheck.value = checkedRoles;
    // console.log(checkedRoles);
}


function checkChange() {
    getCheckedData();

}


async function getMenuListTree() {
    const data = {
        platformId: platformId.value
    }
    proxy.$Request.get(proxy.$urlApi.menu.listTree, data)
        .then((res) => {
            dataArray.value = res.data.data;
            //console.log(dataArray.value);
        }).catch(error => {
        });
}


function deleteRole(row) {
    loading.value = true;
    const data = {
        id: row.id
    }
    proxy.$Request.delete(proxy.$urlApi.role.delete, data)
        .then((res) => {
            if (res.data.code == 200) {
                getSubmitList();
                ElMessage({
                    message: row.name + '删除成功',
                    type: 'success',
                })
            } else {
                ElMessage({
                    message: row.name + '删除失败',
                    type: 'error',
                })
            }

            loading.value = false;
        }).catch(error => {
            // 处理 Promise 拒绝的情况
            // console.error(error); // 输出错误信息
            loading.value = false;
        });
}


//新增or编辑
const dialogVisible = ref(false)
const visibleTitle = ref('');
function setDialogVisible(index) {
    roleArray.value = [];//查询出来的权限数据
    roleArrayCheck.value = [];//查询出来并且选中的数组
    roleList.value = [];//用户拥有的权限列表
    roleBasicsArr.value = [];//基础权限
    roleBasicsArrayCheck.value = [];//选好的基础权限
    getBasicsList();
    if (index == null) {
        reset();
        platformId.value = queryParams.value.platformId;
        visibleTitle.value = "新增角色"
        getMenuListTree();
    } else {
        form.value = {
            id: index.id,
            authIds: index.authIds,
            name: index.name,
            platformId: index.platformId,
            remark: index.remark,
            updateTime: index.updateTime
        };
        visibleTitle.value = "编辑角色"
        //将查询出的角色数据处理为数组
        if (form.value.authIds != null) {
            const arrObject = form.value.authIds.split(',');//分为数组
            roleList.value = arrObject.map((str) => {
                return { id: (str * 1), name: "" };
            });
        }

    }
    dialogVisible.value = true;
}


function reset() {//重置数据
    form.value = {
        id: null,
        name: null,
        remark: null,
        platformId: null,
        authIds: null,
    }
    // if (userData.value.platform != null) {
    form.value.platformId = userData.value.platform.id;
    // }
}




//分页
function currentChange(num) {
    queryParams.value.page = num;
    getSubmitList();
}


//获取平台id
function getPlatformName(id) {
    const data = platformList.value;
    const item = data.find(item => item.id === id);
    return item ? item.name : null;
}



//获取平台集合
const platformList = ref([]);
function getPlatformList() {
    const data = {
        enable: 1
    }
    proxy.$Request.get(proxy.$urlApi.platform.list, data)
        .then((res) => {
            if (res.data.code == 200) {
                platformList.value = res.data.data;
            }
            //console.log(res);
        }).catch(error => {
        });
}




</script>
<style lang="scss">
.role-box {

    .role-tree-box {

        .tree-border {
            width: 100%;
        }

        .role-tree {
            height: 200px;
            width: 400px;
        }

        .role-right {
            padding: 10px;
            color: black;
            width: 150px;
            background: #e7e7e7;

            .el-checkbox {
                display: block;
            }
        }
    }


}

.p-menu {
    background: #F9FAFA;
    margin: 30px;
    height: 40px;
    // width:100%;
}

.p-i1,
.p-i2,
.p-i3 {
    margin-right: 10px;
    color: black;
    height: 40px;

}


.p-i2 {
    width: 194px;
}

.p-i2 .el-input__wrapper {
    height: 38px;
    width: 194px;
    margin-right: 10px;
    color: black;
}

.p-i1 {
    width: 271.49px;
}


.p-button {
    color: white;
    width: 92px;
    height: 40px;
}

.el-input__inner::placeholder {
    color: #999 !important;
}



.p-ul-box {
    padding: 0 30px;
}

//列表
.el-table__inner-wrapper {
    height: calc(100vh - 300px);
}

.is-leaf.el-table__cell {
    background: #E7F0F3 !important;

}

.el-table__cell {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
}

.cell {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
}

.el-table__row:nth-child(odd) {
    background-color: #FFFFFF;
    /*奇数行的背景颜色*/
}

.el-table__row:nth-child(even) {
    background-color: #F9FAFA;
    /*偶数行的背景颜色*/
}



.p-end {
    font-size: 10px;
    padding-left: 30px;
    color: #9A9DAA;
    margin-top: 20px;
}

.el-dialog__header {
    font-size: 16px;
}

.el-dialog__footer {
    font-size: 16px;
}

.el-input__wrapper {
    font-size: 16px;
}

.p-button-2 {
    background: #74C8CE;
    color: white;
    width: 92px;
    height: 40px;
}

//权限
.role-add {

    .r-list-box {
        height: 80px;
        background: #E7F0F3;

        border-radius: 5px;
    }

    .r-list {
        width: 550px;
        background: #E7F0F3;
        font-size: 16px;
        flex-wrap: wrap;
        min-height: 0px;
        border-radius: 5px;

        .r-li {
            font-size: 14px;
            width: 100px;
            height: 22px;
            background: #5A7C93;
            color: #FFFFFF;
            margin: 5px;
            align-items: center;
            border-radius: 5px;
            cursor: pointer;

            /* 将光标设置为手指 */
            text {
                display: inline;
                padding: 0 10px;
                font-size: 12px;
                border-radius: 5px;
                width: 80px;
                white-space: nowrap;
                /* 防止文本换行 */
                overflow: hidden;
                /* 超出部分隐藏 */
                text-overflow: ellipsis;
                /* 超出部分显示省略号 */
            }

            img {
                width: 14px;
                height: 14px;
                font-size: 10 px;
                padding-right: 5px;
            }

        }
    }
}
</style>
  
